﻿function addLoadEvent(func) {
    var oldonload = window.onload;    
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            oldonload();
            func();
        }
    }
}

function preparePageTabBar() {
    if (!document.getElementsByClassName) return false;

    var tabLinks = document.getElementsByClassName("tab");
    if (!tabLinks.length > 0) return false;

    for (var i = 0; i < tabLinks.length; i++) {
        if (tabLinks[i].nodeName != 'DIV') continue;
        tabLinks[i].onclick = function () {
            return changeTabBarDisplay("tab");
        }
    }
}

function changeTabBarDisplay(classname) {
    if (!document.getElementsByClassName) return;
    var tabDivs = document.getElementsByClassName(classname);
    if (tabDivs.length <= 0) return;

    for (var i = 0; i < tabDivs.length; i++) {
        changeCssClass(tabDivs[i], "tab-selected");
    }
}

function changeCssClass(tabDiv, classname) {
    if (!document.getElementsByClassName) return;
    if (tabDiv.nodeName != 'DIV') return;

    var classNames = tabDiv.className.split(/\s+/);
    var pos = -1;
    for (var i = 0; i < classNames.length; i++) {
        if (classNames[i] == classname) {
            pos = i;
            break;
        }
    }

    if (pos >= 0) {
        classNames.splice(i, 1);
    } else {
        classNames.splice(classNames.length - 1, 0, classname);
    }

    tabDiv.className = classNames.join(" ");
    return true;
}

addLoadEvent(preparePageTabBar);